/**
 * UIManager - UI管理器
 * 负责界面渲染、状态管理、推荐工具展示等
 */

class UIManager {
    constructor() {
        this.isLoggedIn = false;
        this.currentUser = null;
        this.currentView = 'recommended'; // 'recommended' | 'personal'
    }

    /**
     * 设置登录状态
     */
    setLoginState(isLoggedIn, user = null) {
        this.isLoggedIn = isLoggedIn;
        this.currentUser = user;
        this.updateAuthUI();
    }

    /**
     * 更新认证相关UI
     */
    updateAuthUI() {
        const loginBtn = document.getElementById('loginBtn');
        const registerBtn = document.getElementById('registerBtn');
        const userMenu = document.getElementById('userMenu');
        const usernameElement = document.getElementById('currentUsername');
        const personalSection = document.getElementById('personalSection');
        const bookmarksSection = document.getElementById('bookmarksSection');
        const recommendedSection = document.getElementById('recommendedSection');
        const userFeaturesInfo = document.getElementById('userFeaturesInfo');
        
        if (this.isLoggedIn) {
            // 已登录状态
            if (loginBtn) loginBtn.style.display = 'none';
            if (registerBtn) registerBtn.style.display = 'none';
            if (userMenu) userMenu.style.display = 'block';
            
            // 显示用户名
            if (usernameElement && this.currentUser) {
                usernameElement.textContent = this.currentUser.username;
            }
            
            // 默认显示我的收藏
            if (userFeaturesInfo) userFeaturesInfo.style.display = 'none';
            if (personalSection) personalSection.style.display = 'block';
            if (bookmarksSection) bookmarksSection.style.display = 'block';
            if (recommendedSection) recommendedSection.style.display = 'none';
            
            this.currentView = 'personal';
        } else {
            // 未登录状态
            if (loginBtn) loginBtn.style.display = 'flex';
            if (registerBtn) registerBtn.style.display = 'flex';
            if (userMenu) userMenu.style.display = 'none';
            
            // 显示功能介绍和推荐工具
            if (userFeaturesInfo) userFeaturesInfo.style.display = 'block';
            if (recommendedSection) recommendedSection.style.display = 'block';
            if (personalSection) personalSection.style.display = 'none';
            if (bookmarksSection) bookmarksSection.style.display = 'none';
            
            this.currentView = 'recommended';
        }
    }

    /**
     * 显示个人收藏页面
     */
    showPersonalBookmarks() {
        const recommendedSection = document.getElementById('recommendedSection');
        const personalSection = document.getElementById('personalSection');
        const bookmarksSection = document.getElementById('bookmarksSection');
        const userFeaturesInfo = document.getElementById('userFeaturesInfo');
        
        if (recommendedSection) recommendedSection.style.display = 'none';
        if (userFeaturesInfo) userFeaturesInfo.style.display = 'none';
        if (personalSection) personalSection.style.display = 'block';
        if (bookmarksSection) bookmarksSection.style.display = 'block';
        
        this.currentView = 'personal';
        document.title = '我的收藏 - 云书签';
        this.closeUserDropdown();
    }

    /**
     * 显示推荐导航页面
     */
    showRecommendedNavigation() {
        const recommendedSection = document.getElementById('recommendedSection');
        const personalSection = document.getElementById('personalSection');
        const bookmarksSection = document.getElementById('bookmarksSection');
        const userFeaturesInfo = document.getElementById('userFeaturesInfo');
        
        if (recommendedSection) recommendedSection.style.display = 'block';
        
        // 只有未登录才显示功能介绍
        if (userFeaturesInfo) {
            userFeaturesInfo.style.display = this.isLoggedIn ? 'none' : 'block';
        }
        
        if (personalSection) personalSection.style.display = 'none';
        if (bookmarksSection) bookmarksSection.style.display = 'none';
        
        this.currentView = 'recommended';
        document.title = '推荐导航 - 云书签';
        this.closeUserDropdown();
    }

    /**
     * 切换用户下拉菜单
     */
    toggleUserDropdown() {
        const dropdown = document.getElementById('userDropdown');
        if (dropdown) {
            dropdown.classList.toggle('show');
        }
    }

    /**
     * 关闭用户下拉菜单
     */
    closeUserDropdown() {
        const dropdown = document.getElementById('userDropdown');
        if (dropdown) {
            dropdown.classList.remove('show');
        }
    }

    /**
     * 渲染推荐工具
     */
    renderRecommendedTools() {
        this.renderToolsCategory('efficiencyTools', recommendedTools.efficiencyTools);
        this.renderToolsCategory('learningResources', recommendedTools.learningResources);
        this.renderToolsCategory('devTools', recommendedTools.devTools);
        this.renderToolsCategory('designTools', recommendedTools.designTools);
        this.renderToolsCategory('aiTools', recommendedTools.aiTools);
        this.renderToolsCategory('lifestyleServicesGrid', recommendedTools.lifestyleServicesExtended);
    }

    /**
     * 渲染月度榜单
     */
    renderMonthlyRankings() {
        // 更新月度标题
        this.updateMonthlyTitle();
        
        this.renderRankingCategory('monthlyEfficiencyTools', recommendedTools.mostClickedSites);
        this.renderRankingCategory('studentEssentialSites', recommendedTools.studentEssentialSites);
        this.renderRankingCategory('aiEssentialTools', recommendedTools.aiEssentialTools);
        this.renderRankingCategory('lifestyleServices', recommendedTools.lifestyleServices);
        
        // 渲染专业分类
        this.renderRankingCategory('developerTools', recommendedTools.developerTools);
        this.renderRankingCategory('designTools', recommendedTools.designTools);
        this.renderRankingCategory('officeTools', recommendedTools.officeTools);
        this.renderRankingCategory('educationTools', recommendedTools.educationTools);
        this.renderRankingCategory('entertainmentTools', recommendedTools.entertainmentTools);
    }

    /**
     * 更新月度标题
     */
    updateMonthlyTitle() {
        const monthInfo = recommendedTools.getCurrentMonth();
        const titleElement = document.querySelector('.monthly-rankings .ranking-title h3');
        
        if (titleElement) {
            titleElement.innerHTML = `<i class="fas fa-fire"></i> 全网推荐 Top 10`;
        }
    }

    /**
     * 渲染工具分类
     */
    renderToolsCategory(containerId, tools) {
        const container = document.getElementById(containerId);
        if (!container) return;
        
        container.innerHTML = tools.map(tool => `
            <div class="tool-item ${tool.isAffiliate ? 'affiliate-item' : ''}" onclick="openWebsite('${tool.url}')">
                <div class="tool-header">
                    <div class="tool-icon" style="background-color: ${tool.color}">
                        <i class="${tool.icon}"></i>
                    </div>
                    <div class="tool-title">
                        ${escapeHtml(tool.name)}
                        ${tool.isAffiliate ? '<span class="affiliate-badge">优惠</span>' : ''}
                    </div>
                </div>
                <div class="tool-description">${escapeHtml(tool.description)}</div>
                <div class="tool-meta">
                    <div class="tool-tags">
                        ${tool.tags.map(tag => `<span class="tool-tag">${escapeHtml(tag)}</span>`).join('')}
                    </div>
                    <a href="${tool.url}" target="_blank" class="tool-external" onclick="event.stopPropagation()">
                        <i class="fas fa-external-link-alt"></i>
                    </a>
                </div>
            </div>
        `).join('');
    }

    /**
     * 渲染榜单分类
     */
    renderRankingCategory(containerId, tools) {
        const container = document.getElementById(containerId);
        if (!container) return;
        
        container.innerHTML = tools.map(tool => `
            <div class="tool-item ${tool.isAffiliate ? 'affiliate-item' : ''}" onclick="openWebsite('${tool.url}')">
                <div class="tool-header">
                    <div class="tool-icon" style="background-color: ${tool.color}">
                        <i class="${tool.icon}"></i>
                    </div>
                    <div class="tool-title">
                        ${escapeHtml(tool.name)}
                        ${tool.isAffiliate ? '<span class="affiliate-badge">优惠</span>' : ''}
                    </div>
                    ${tool.ranking ? `<div class="ranking-number">#${tool.ranking}</div>` : ''}
                </div>
                <div class="tool-description">${escapeHtml(tool.description)}</div>
                <div class="tool-meta">
                    <div class="tool-tags">
                        ${tool.tags.map(tag => `<span class="tool-tag">${escapeHtml(tag)}</span>`).join('')}
                    </div>
                    <a href="${tool.url}" target="_blank" class="tool-external" onclick="event.stopPropagation()">
                        <i class="fas fa-external-link-alt"></i>
                    </a>
                </div>
            </div>
        `).join('');
    }

    /**
     * 初始化分类标签页
     */
    initializeCategoryTabs() {
        const tabs = document.querySelectorAll('.category-tab');
        tabs.forEach(tab => {
            tab.addEventListener('click', () => {
                this.switchCategoryTab(tab.dataset.category);
            });
        });
    }

    /**
     * 切换分类标签页
     */
    switchCategoryTab(category) {
        // 更新标签状态
        const tabs = document.querySelectorAll('.category-tab');
        tabs.forEach(tab => {
            tab.classList.remove('active');
            if (tab.dataset.category === category) {
                tab.classList.add('active');
            }
        });

        // 更新内容区域
        const sections = document.querySelectorAll('.category-section');
        sections.forEach(section => {
            section.classList.remove('active');
            if (section.dataset.category === category) {
                section.classList.add('active');
            }
        });
    }

    /**
     * 渲染智能推荐
     */
    renderSmartRecommendations(recommendations) {
        const container = document.getElementById('smartRecommendations');
        const personalizedSection = document.getElementById('personalizedRecommendations');
        
        if (!container || !recommendations || recommendations.length === 0) {
            if (personalizedSection) personalizedSection.style.display = 'none';
            return;
        }
        
        container.innerHTML = recommendations.map(tool => `
            <div class="tool-item" onclick="openWebsite('${tool.url}')">
                <div class="tool-header">
                    <div class="tool-icon" style="background-color: ${tool.color}">
                        <i class="${tool.icon}"></i>
                    </div>
                    <div class="tool-title">${escapeHtml(tool.name)}</div>
                </div>
                <div class="tool-description">${escapeHtml(tool.description)}</div>
                <div class="tool-meta">
                    <div class="tool-tags">
                        ${tool.tags.map(tag => `<span class="tool-tag">${escapeHtml(tag)}</span>`).join('')}
                    </div>
                    <a href="${tool.url}" target="_blank" class="tool-external" onclick="event.stopPropagation()">
                        <i class="fas fa-external-link-alt"></i>
                    </a>
                </div>
            </div>
        `).join('');
        
        if (personalizedSection) personalizedSection.style.display = 'block';
    }

    /**
     * 初始化事件监听
     */
    initializeEventListeners() {
        // 点击外部关闭下拉菜单
        document.addEventListener('click', (e) => {
            if (!e.target.closest('.user-menu')) {
                this.closeUserDropdown();
            }
        });
    }
}

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = UIManager;
}

